<template>
  <a-modal
    v-model:open="visible"
    title="创建/修改图片"
    :footer="null"
    @cancel="handleCancel"
    width="800px"
  >
    <div id="addPicturePage">
      <h2 style="margin-bottom: 16px">
        {{ picture?.id ? '修改图片' : '创建图片' }}
      </h2>

      <a-typography-paragraph v-if="spaceId" type="secondary">
        保存至空间：<a :href="`/picture/space/${spaceId}`" target="_blank">{{ space?.spaceName }}</a>
        <br/>
        占用容量：{{ formatSize(space?.totalSize ?? 0) }} / {{ formatSize(space?.maxSize ?? 0) }}
      </a-typography-paragraph>

      <a-tabs v-model:activeKey="uploadType">
        <a-tab-pane key="file" tab="文件上传">
          <UploadPicture :picture="picture" :spaceId="spaceId" :onSuccess="onSuccess" />
        </a-tab-pane>
        <a-tab-pane key="url" tab="URL 上传">
          <URLUploadPicture :picture="picture" :spaceId="spaceId" :onSuccess="onSuccess" />
        </a-tab-pane>
      </a-tabs>

      <a-form v-if="picture" layout="vertical" :model="pictureForm" @finish="handleSubmit">
        <a-form-item label="名称" name="name">
          <a-input v-model:value="pictureForm.name" placeholder="请输入名称" />
        </a-form-item>
        <a-form-item label="简介" name="introduction">
          <a-textarea
            v-model:value="pictureForm.introduction"
            placeholder="请输入简介"
            :auto-size="{ minRows: 1, maxRows: 5 }"
            allowClear
          />
        </a-form-item>
        <a-form-item label="分类" name="category">
          <a-auto-complete
            v-model:value="pictureForm.category"
            :options="categoryOptions"
            placeholder="请输入分类"
            allowClear
          />
        </a-form-item>
        <a-form-item label="标签" name="tags">
          <a-select
            v-model:value="pictureForm.tags"
            :options="tagOptions"
            mode="tags"
            placeholder="请输入标签"
            allowClear
          />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" html-type="submit" style="width: 100%">提交</a-button>
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue'
import UploadPicture from '@/components/UploadPicture.vue'
import URLUploadPicture from '@/components/URLUploadPicture.vue'
import {
  editPictureUsingPost,
  getPictureVoByIdUsingGet,
  listPictureTagCategoryUsingGet
} from '@/api/pictureController'
import { message } from 'ant-design-vue'
import { getSpaceVoByIdUsingGet } from '@/api/spaceController'
import { formatSize } from '@/utils'

const props = defineProps<{
  modelValue: boolean
  spaceId?: number | string
  pictureId?: number | string
}>()

const emit = defineEmits(['update:modelValue', 'success'])

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const picture = ref<API.PictureVO>()
const pictureForm = reactive<API.PictureEditRequestDTO>({})
const categoryOptions = ref<string[]>([])
const tagOptions = ref<string[]>([])
const uploadType = ref<'file' | 'url'>('file')
const space = ref<API.SpaceVO>({})

const fetchSpaceDetail = async () => {
  if (!props.spaceId) return
  try {
    const res = await getSpaceVoByIdUsingGet({ id: props.spaceId })
    if (res.data.code === 0 && res.data.data) {
      space.value = res.data.data
    }
  } catch (e: any) {
    message.error('获取空间信息失败：' + e.message)
  }
}

const onSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
  pictureForm.name = newPicture.name
}

const handleSubmit = async (values: any) => {
  const pictureId = picture.value?.id
  if (!pictureId) return

  const res = await editPictureUsingPost({
    id: pictureId,
    spaceId: props.spaceId as number,
    ...values
  })

  if (res.data.code === 0 && res.data.data) {
    message.success('操作成功')
    emit('success')
    visible.value = false
  } else {
    message.error('操作失败，' + res.data.message)
  }
}

const getTagCategoryOptions = async () => {
  const res = await listPictureTagCategoryUsingGet()
  if (res.data.code === 0 && res.data.data) {
    tagOptions.value = (res.data.data.tagList ?? []).map((data: string) => ({ value: data, label: data }))
    categoryOptions.value = (res.data.data.categoryList ?? []).map((data: string) => ({ value: data, label: data }))
  } else {
    message.error('加载选项失败，' + res.data.message)
  }
}

const getOldPicture = async () => {
  const id = props.pictureId
  if (id) {
    const res = await getPictureVoByIdUsingGet({ id })
    if (res.data.code === 0 && res.data.data) {
      const data = res.data.data
      picture.value = data
      pictureForm.name = data.name
      pictureForm.introduction = data.introduction
      pictureForm.category = data.category
      pictureForm.tags = data.tags
    }
  }
}

onMounted(() => {
  getTagCategoryOptions()
  getOldPicture()
  fetchSpaceDetail()
})

const handleCancel = () => {
  // 可选：重置表单等
}
</script>

<style scoped>
#addPicturePage {
  max-width: 720px;
  margin: 0 auto;
}
</style>
